<?php

require_once '../data/data.php';

//只支持POST请求，否则返回405错误
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
	header('HTTP/1.1 405 Method Not Allowed');
	return;
}

session_start();

$userName = isset($_POST['userName']) ?htmlspecialchars($_POST['userName']) : '';
$password = isset($_POST['password']) ?htmlspecialchars($_POST['password']) : '';
$pwdConfirm = isset($_POST['pwdConfirm']) ?htmlspecialchars($_POST['pwdConfirm']) : '';

//非空验证，以及两次输入的密码是否一致，用户是否已被注册
$hasError = false;
$inputBag = [
	'userName' => ''
];
$errorBag = [
	'userName' => '',
	'password' => '',
	'pwdConfirm' => ''
];
if (trim($userName) == '') {
	$hasError = true;
	$errorBag['userName'] = 'The username cannot be empty';
}
if (strlen($password) < 6) {
	$hasError = true;
	$errorBag['password'] = 'The password cannot be less than six';
}
if ($password !== $pwdConfirm) {
	$hasError = true;
	$errorBag['pwdConfirm'] = 'password must be same';
}
// 验证用户名是否已经被注册
$sql = 'select id from `users` where user_name=?';
$data = query($sql, [$userName]);
if (count($data) > 0) {
    $hasError = true;
    $errorBag['userName'] = 'This account has already signed up';
}

//如果数据验证出现错误，则把错误包存入session，重定向到表单页面
$inputBag['userName'] = $userName;
$_SESSION['has_error'] = $hasError;
$_SESSION['error_bag'] = $errorBag;
$_SESSION['input_bag'] = $inputBag;
if ($hasError) {
   // 重定向
   header('Location:../../public/register.php?op=1');
   return;
}

// 验证通过，写入数据库
$password = password_hash($password, PASSWORD_BCRYPT);
$sql = 'insert into users(user_name,password,register_time) values(?,?,now())';
$args = [$userName, $password];
if (execute($sql, $args)) {
   header('Location:../../public/register.php?op=2');
} else {
   header('Location:../../public/register.php?op=1');
}
